﻿using System.Collections;
using System.Windows;
using System.Windows.Controls;

namespace Utils.Wpf
{
	public class ListBoxMultipleSelector
	{
		public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached("SelectedItems", typeof (IList), typeof (ListBoxMultipleSelector), new PropertyMetadata(null, (OnSelectedItemsChanged)));

		public static IList GetSelectedItems(DependencyObject dependencyObject)
		{
			return (IList)dependencyObject.GetValue(SelectedItemsProperty);
		}

		public static void SetSelectedItems(DependencyObject dependencyObject, IList value)
		{
			dependencyObject.SetValue(SelectedItemsProperty, value);
		}

		private static void OnSelectedItemsChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
		{
			ListBox listBox = (ListBox)dependencyObject;
			ListBoxMultipleSelector.ReSetSelectedItems(listBox);
			listBox.SelectionChanged += delegate
			{
				ListBoxMultipleSelector.ReSetSelectedItems(listBox);
			};
		}

		private static void ReSetSelectedItems(ListBox listBox)
		{
			IList selectedItems = ListBoxMultipleSelector.GetSelectedItems(listBox);
			selectedItems.Clear();
			if (listBox.SelectedItems != null)
			{
				foreach (object item in listBox.SelectedItems)
				{
					selectedItems.Add(item);
				}
					
			}
		}
	}
}
